package com.conversationboard.controller;

import java.io.IOException;
import java.security.Principal;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.joda.time.DateTime;

import com.conversationboard.model.Search;
import com.conversationboard.model.SearchResult;
import com.conversationboard.model.SearchResultUtilities;
import com.conversationboard.model.User;

@WebServlet(name = "ThreadsInMonthControllerServlet", urlPatterns = "/ThreadsInMonthControllerServlet")
public class ThreadsInMonthControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 5698905079580977122L;


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		try {

			Principal principal = request.getUserPrincipal();
			User user = null;

			if (principal != null) {
				user = User.get(principal.getName());
			} else {
				user = User.getAnonymousUser();
			}

			Locale locale = request.getLocale();
			user.setLocale(locale);

			int year = Integer.parseInt(request.getParameter("year"));
			int month = Integer.parseInt(request.getParameter("month"));
			int offset = Integer.parseInt(request.getParameter("offset"));

			List<SearchResult> results = new ArrayList<SearchResult>(100);
			Search search = new Search();

			SimpleDateFormat dateFormat = new SimpleDateFormat("MMMMMMMMMMMM yyyy");
			DateTime date = new DateTime(year, month, 1, 0, 0, 0, 0);

			results = search.getThreadsInMonth(year, month, offset);
			request.setAttribute("searchresults", results);
			request.setAttribute("year", (year + ""));
			request.setAttribute("month", (month + ""));
			request.setAttribute("offset", offset);
			request.setAttribute("user", user);
			request.setAttribute("displaydate", dateFormat.format(date.toDate()));

			SearchResultUtilities.removePrivateThreads(results, user);

			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/viewthreadsbymonthresults.jsp");
			dispatcher.forward(request, response);

		} catch (NumberFormatException e) {
			/* Do nothing */
		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
